package com.mall.mymall.common;

import io.lettuce.core.resource.ClientResources;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnection;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;

import java.time.Duration;

@Configuration
public class MyRedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private Integer port;
//    @Bean
//    public RedisConnectionFactory redisConnectionFactory() {
//        // 基于netty 异步 适用于高并发 nio
//        return new LettuceConnectionFactory();
//        // 传统阻塞io流 并发量低

    /// /        return new JedisConnectionFactory();
//    }
    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory() {
        System.out.println("lettuceConnectionFactory created" + "\nConnection to: " + "host:" + host + "\n" + "port:" + port);
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);
        redisStandaloneConfiguration.setDatabase(0);
        GenericObjectPoolConfig<LettuceConnection> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxTotal(8); // 最大连接数
        poolConfig.setMaxIdle(4); // 最大空闲连接数
        poolConfig.setMinIdle(0); // 最小空闲连接数
        poolConfig.setMaxWait(Duration.ofMillis(1000)); // 最大等待时间
        LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder()
                .poolConfig(poolConfig).build();

        return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfiguration);
    }

    @Bean
    public ChannelTopic topic() {
        // 监听渠道
        return new ChannelTopic("my-mall");
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate() {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂
        redisTemplate.setConnectionFactory(lettuceConnectionFactory());
        // 设置序列化方式 这里略过 全部使用fastJSON进行序列化和反序列化
        return redisTemplate;
    }
}
